package top.yueyazhui.learn_shiro_spring_boot.realm;

import cn.hutool.core.util.ObjectUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.yueyazhui.learn_shiro_spring_boot.entity.User;
import top.yueyazhui.learn_shiro_spring_boot.service.UserService;

/**
 * @Author yueyazhui
 * @Date 2023/2/25
 *
 * 继承 AuthenticatingRealm 可以实现认证功能
 * 继承 AuthorizingRealm 可以实现认证、授权功能
 */
@Component
public class MyRealm02 extends AuthorizingRealm {

    @Autowired
    UserService userService;

    /**
     * 核心方法：根据用户输入的用户名去数据库查询用户信息（认证）
     *
     * @param authenticationToken 包含用户登录时输入的用户名和密码等信息
     * @return 从数据库中查询到的用户信息
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        // 获取用户登录时输入的用户名
        String username = usernamePasswordToken.getUsername();
        User user = userService.getUserByUsername(username);
        if (ObjectUtil.isNull(user)) {
            throw new UnknownAccountException("用户名输入错误");
        }
        // 返回查询到的用户信息（用户名、密码、盐）
        return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
    }

    /**
     * 返回用户的角色和权限（授权）
     * @param principalCollection 含有用户的登录信息
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取登录用户
        String username = (String) principalCollection.getPrimaryPrincipal();
        return new SimpleAuthorizationInfo(userService.findRolesByUsername(username));
    }
}
